package com.zl.roomdesign.main

import android.app.AlertDialog
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.widget.EditText
import com.zl.core.api.ServiceGenerator
import com.zl.core.base.ModeActivity
import com.zl.roomdesign.R
import kotlinx.android.synthetic.main.activity_image_list.*
import android.provider.MediaStore
import android.util.Log
import com.zl.core.extend.toTextString
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File


/**
 *
 *<p></p>
 *
 * Created by zhangli on 2018/6/6 15:24.<br/>
 */
class ImageListActivity : ModeActivity() {

    override fun layoutId() = R.layout.activity_image_list

    private val api = ServiceGenerator.createRxService(MainApi::class.java)

    val list: MutableList<ImgEntity> = mutableListOf()
    lateinit var mAdapter: ImageListAdapter

    override fun initView(savedInstanceState: Bundle?) {
        mAdapter = ImageListAdapter(list) {
            val position = it.adapterPosition
            list[position].check = !list[position].check
            mAdapter.notifyItemChanged(position)
        }
        recyclerView.layoutManager = GridLayoutManager(this, 3)
        recyclerView.adapter = mAdapter
    }

    override fun setListener() {

        doneImg.setOnClickListener {
            val view = EditText(this)
            view.setText("其他")
            AlertDialog.Builder(this)
                    .setTitle("设置分类")
                    .setView(view)
                    .setPositiveButton("上传", { _, _ ->
                        upload(view.toTextString())
                    })
                    .show()
        }
    }

    private fun upload(kind: String) {

        val files: MutableMap<String, RequestBody> = mutableMapOf()
        for (entity in list) {
            if (entity.check) {
                val file = File(entity.fileName)
                val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
                files["file\"; filename=\"" + entity.name] = requestBody
            }
        }

        val map = mapOf(pair = Pair("kind", kind))
        api.uploadMultiMaterial(files, map)
                .map {
                    if (it.code == 0) {
                        return@map it.data
                    } else {
                        throw RuntimeException("error" + it.message)
                    }
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe {
                    showLoading()
                }
                .doOnTerminate {
                    hideLoading()
                }
                .subscribe({
                    showToastSafe("ok")
                    finish()
                }, {
                    showToastSafe(it.message + "")
                })
    }

    override fun observe() {

    }

    var i = 0
    override fun afterView() {
        val cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null)
        while (cursor!!.moveToNext()) {

            try {
                val name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME))
                val indexOrThrow = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                val path = cursor.getString(indexOrThrow)
                list.add(ImgEntity(path, name))
            } catch (e: Exception) {
            }
        }
        cursor.close()
        mAdapter.notifyDataSetChanged()
    }
}